package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.soap.MTOM;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/9/24 10:52
 */
public class BaseController extends HttpServlet {
    /**
     * 分发
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String methodName = req.getParameter("method");
        if (methodName == null || "".equals(methodName)) {
            methodName = "index";
        }
        System.out.println("methodName不为空："+methodName);
        //1.获取请求路径
//        String uri = req.getRequestURI();
        //2.截取
//        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        //3.通过名字获得method对象

//        Method method = null;
//        try {
//            method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        }

        //4.执行方法，传入调用方法的对象以及方法的参数
        try {
            Method method =  this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Object result = method.invoke(this, req, resp);


            if (result != null) {

                String res = (String) result;
                System.out.println(res);
//            if (res == null) {
//                //如果传入的methodName不匹配，转发到主页
//                req.getRequestDispatcher("/index.jsp").forward(req, resp);
//            }
            //5.响应（转发；重定向；返回json，返回字节（response.getOutputStream().write(null);））
                String path = res.substring(res.indexOf(":") + 1);
                //转发 重定向 字符串
                if (res.startsWith(Constants.FORWARD)) {
                    //转发   forward:/xxx
                    req.getRequestDispatcher(path).forward(req, resp);
                } else if (res.startsWith(Constants.REDIRECT)) {
                    //重定向
                    resp.sendRedirect(req.getContextPath()+path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("baseservlet异常");
            //如果传入的methodName不匹配，重定向到错误信息页面
            req.getSession().setAttribute("msg", "程序异常！请稍后再试！");
            resp.sendRedirect("/message.jsp");

        }


    }


    /**
     * 直接传入对象序列化为json，并返回给客户端
     *
     * @param obj
     * @param response
     * @throws IOException
     */
    public void writeValue(Object obj, HttpServletResponse response) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(), obj);
    }

    /**
     * 当method的value不匹配时，默认index访问每个controller的index()
     * @param req
     * @param resp
     * @return
     */
    public String index(HttpServletRequest req,HttpServletResponse resp) {
        return Constants.FORWARD + "/index.jsp";
    }


}
